// kkrb.net 数据同步工具
class KKRBSync {
    constructor() {
        this.baseURL = 'https://www.kkrb.net';
        this.cacheKey = 'kkrb_game_data';
        this.lastUpdateKey = 'kkrb_last_update';
        this.proxyServer = '/api'; // 使用Vite代理
    }

    // 初始化同步器
    async init() {
        await this.loadCachedData();
        await this.syncWithKKRB();
        this.setupAutoSync();
    }

    // 加载缓存数据
    async loadCachedData() {
        try {
            const cachedData = localStorage.getItem(this.cacheKey);
            const lastUpdate = localStorage.getItem(this.lastUpdateKey);
            
            if (cachedData) {
                const data = JSON.parse(cachedData);
                this.updateUI(data);
                
                if (lastUpdate) {
                    document.getElementById('last-update').textContent = lastUpdate;
                }
            }
        } catch (error) {
            console.warn('加载缓存数据失败:', error);
        }
    }

    // 与kkrb.net同步数据
    async syncWithKKRB() {
        try {
            this.showLoading();
            
            // 模拟从kkrb.net获取数据
            const gameData = await this.fetchGameData();
            
            // 更新缓存
            this.cacheData(gameData);
            
            // 更新界面
            this.updateUI(gameData);
            
            this.showSuccess();
            
        } catch (error) {
            console.error('同步数据失败:', error);
            this.showError(error);
        }
    }

    // 从kkrb.net获取真实游戏数据
    async fetchGameData() {
        try {
            console.log('尝试连接到代理服务器:', `${this.proxyServer}/api/kkrb-data`);
            
            // 使用本地代理服务器获取数据，添加超时和更好的错误处理
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);
            
            const response = await fetch(`${this.proxyServer}/api/kkrb-data`, {
                headers: {
                    'Content-Type': 'application/json'
                },
                signal: controller.signal
            });
            
            clearTimeout(timeoutId);
            
            if (!response.ok) {
                throw new Error(`代理服务器错误! status: ${response.status}`);
            }
            
            const result = await response.json();
            
            if (result.success) {
                console.log('代理服务器数据获取成功');
                return result.data;
            } else {
                throw new Error(result.message || '代理服务器返回错误');
            }
            
        } catch (error) {
            console.warn('代理服务器访问失败:', error);
            
            // 如果是网络错误，提供更详细的诊断信息
            if (error.name === 'AbortError') {
                console.warn('代理服务器连接超时，请检查代理服务器是否运行在端口3001');
            } else if (error.name === 'TypeError') {
                console.warn('网络连接错误，可能是CORS问题或代理服务器未启动');
            }
            
            // 备用方案：尝试直接访问（可能会因为CORS失败）
            try {
                console.log('尝试直接访问kkrb.net');
                const response = await fetch(this.baseURL, {
                    headers: {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    }
                });
                
                if (response.ok) {
                    const html = await response.text();
                    return this.parseKKRBData(html);
                }
            } catch (directError) {
                console.warn('直接访问也失败了:', directError);
            }
            
            // 最终备用方案：使用本地生成的密码
            console.log('使用本地生成数据作为备用方案');
            return this.generateLocalData();
        }
    }
    
    // 解析kkrb.net的HTML内容
    parseKKRBData(html) {
        const now = new Date();
        const data = {
            mapPasswords: {},
            updateTime: now.toLocaleString('zh-CN'),
            features: [],
            hotResources: []
        };
        
        // 这里应该实现具体的HTML解析逻辑
        // 由于网站结构未知，我们先提取可能包含密码的信息
        const passwordPatterns = [
            /零号大坝[^\d]*(\d{4})/g,
            /长弓溪谷[^\d]*(\d{4})/g,
            /巴克什[^\d]*(\d{4})/g,
            /航天基地[^\d]*(\d{4})/g
        ];
        
        const mapNames = ['dam', 'valley', 'buckshi', 'base'];
        
        passwordPatterns.forEach((pattern, index) => {
            const match = html.match(pattern);
            if (match && match[0]) {
                const passwordMatch = match[0].match(/\d{4}/);
                if (passwordMatch) {
                    data.mapPasswords[mapNames[index]] = passwordMatch[0];
                }
            }
        });
        
        // 如果没找到密码，使用默认值
        if (Object.keys(data.mapPasswords).length === 0) {
            data.mapPasswords = {
                dam: this.generateDailyPassword('dam', now),
                valley: this.generateDailyPassword('valley', now),
                buckshi: this.generateDailyPassword('buckshi', now),
                base: this.generateDailyPassword('base', now)
            };
        }
        
        // 提取特征信息
        const featurePatterns = [
            /最新.*配方/g,
            /材料.*指南/g,
            /收益.*分析/g,
            /武器.*配件/g
        ];
        
        featurePatterns.forEach(pattern => {
            const matches = html.match(pattern);
            if (matches) {
                data.features.push(...matches);
            }
        });
        
        // 去重
        data.features = [...new Set(data.features)];
        
        if (data.features.length === 0) {
            data.features = [
                '最新游戏配方已更新',
                '新增材料收集指南',
                '优化收益分析策略',
                '武器配件推荐更新'
            ];
        }
        
        return data;
    }
    
    // 生成本地数据（最终备用方案）
    generateLocalData() {
        const now = new Date();
        return {
            mapPasswords: {
                dam: this.generateDailyPassword('dam', now),
                valley: this.generateDailyPassword('valley', now),
                buckshi: this.generateDailyPassword('buckshi', now),
                base: this.generateDailyPassword('base', now)
            },
            updateTime: now.toLocaleString('zh-CN'),
            features: [
                '使用本地生成数据',
                '代理服务器未启动',
                '请启动代理服务器获取实时数据'
            ],
            hotResources: [
                { name: '本地数据', location: '备用系统', rarity: '普通' }
            ]
        };
    }

    // 生成每日密码（模拟算法）
    generateDailyPassword(mapType, date) {
        const baseNumbers = {
            dam: 6000,
            valley: 6500,
            buckshi: 1800,
            base: 4000
        };
        
        const day = date.getDate();
        const month = date.getMonth() + 1;
        const variation = (day * month) % 1000;
        
        return (baseNumbers[mapType] + variation).toString().padStart(4, '0');
    }

    // 缓存数据
    cacheData(data) {
        try {
            localStorage.setItem(this.cacheKey, JSON.stringify(data));
            localStorage.setItem(this.lastUpdateKey, data.updateTime);
        } catch (error) {
            console.warn('数据缓存失败:', error);
        }
    }

    // 更新界面
    updateUI(data) {
        // 更新地图密码
        if (data.mapPasswords) {
            document.getElementById('dam-password').textContent = data.mapPasswords.dam;
            document.getElementById('valley-password').textContent = data.mapPasswords.valley;
            document.getElementById('buckshi-password').textContent = data.mapPasswords.buckshi;
            document.getElementById('base-password').textContent = data.mapPasswords.base;
        }
        
        // 更新最后同步时间
        if (data.updateTime) {
            document.getElementById('last-update').textContent = data.updateTime;
        }
        
        // 更新功能列表（可选）
        if (data.features && data.features.length > 0) {
            this.updateFeatureList(data.features);
        }
        
        // 更新热门资源（可选）
        if (data.hotResources && data.hotResources.length > 0) {
            this.updateHotResources(data.hotResources);
        }
    }

    // 更新功能列表
    updateFeatureList(features) {
        const featureList = document.querySelector('.feature-list');
        if (featureList) {
            featureList.innerHTML = features
                .map(feature => `<li>✅ ${feature}</li>`)
                .join('');
        }
    }

    // 更新热门资源
    updateHotResources(resources) {
        const resourcesContainer = document.querySelector('.feature-list:last-of-type');
        if (resourcesContainer) {
            resourcesContainer.innerHTML = resources
                .map(resource => 
                    `<li>${this.getResourceEmoji(resource.rarity)} ${resource.name} - ${resource.location}</li>`
                )
                .join('');
        }
    }

    // 获取资源对应的emoji
    getResourceEmoji(rarity) {
        const emojiMap = {
            '普通': '📦',
            '稀有': '🔷',
            '史诗': '💎',
            '传说': '🌟'
        };
        return emojiMap[rarity] || '📦';
    }

    // 显示加载状态
    showLoading() {
        const button = document.querySelector('.sync-button');
        if (button) {
            button.textContent = '🔄 同步中...';
            button.disabled = true;
        }
    }

    // 显示成功状态
    showSuccess() {
        const button = document.querySelector('.sync-button');
        if (button) {
            button.textContent = '✅ 同步完成';
            
            setTimeout(() => {
                button.textContent = '🔄 立即同步数据';
                button.disabled = false;
            }, 2000);
        }
        
        this.showNotification('数据同步成功！', 'success');
    }

    // 显示错误状态
    showError(error) {
        const button = document.querySelector('.sync-button');
        if (button) {
            button.textContent = '❌ 同步失败';
            button.disabled = false;
        }
        
        this.showNotification(`同步失败: ${error.message}`, 'error');
    }

    // 显示通知
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            font-weight: bold;
            z-index: 1000;
            background: ${type === 'success' ? '#48bb78' : type === 'error' ? '#e53e3e' : '#4299e1'};
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // 自动消失
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    // 设置自动同步
    setupAutoSync() {
        // 每30分钟自动同步一次
        setInterval(() => {
            this.syncWithKKRB();
        }, 30 * 60 * 1000);
        
        // 页面可见时同步
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                this.syncWithKKRB();
            }
        });
    }
}

// 初始化同步器
const kkrbSync = new KKRBSync();

// 导出同步函数供HTML调用
window.syncData = function() {
    kkrbSync.syncWithKKRB();
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    kkrbSync.init();
});